package logic

import (
	"context"
	"fmt"
	"person/model/mysql"
	"person/pkg"

	"person/personrpc/internal/svc"
	"person/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PersonAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPersonAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PersonAddLogic {
	return &PersonAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PersonAddLogic) PersonAdd(in *personrpc.PersonAddRequest) (*personrpc.PersonAddResponse, error) {
	// todo: add your logic here and delete this line
	var findPerson mysql.Person
	mysql.DB.Debug().Where("phoned = ?", in.Phone).Find(&findPerson)
	if findPerson.ID != 0 {
		return nil, fmt.Errorf("该账号已存在,请切换账号注册")
	}
	person := mysql.Person{
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	mysql.DB.Debug().Create(&person)
	return &personrpc.PersonAddResponse{
		Id: int64(person.ID),
	}, nil
}
